package repo

import (
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	model "micro-oauth/datamodels"
	"micro-oauth/utils"
	"time"
)

func (s *ServiceImpl)CreatePasswordRule(rule *model.PassWordRule) error {
	sql := `insert into oauth_user_passwd_rule (id,created_by,
			user_id,login_status,passwd_form,passwd_length,passwd_expire,expire_day) 
			values($1,$2,$3,$4,$5,$6,$7,$8)`

	id,_:= utils.GetId()
	rule.Id = id

	formArr,errM := json.Marshal(rule.PassWordForm)
	if errM != nil{
		logrus.Error(errM)
		return errM
	}

	lenArr,errL := json.Marshal(rule.PassWordLength)
	if errL != nil{
		logrus.Error(errL)
		return errL
	}

	if rule.ExpireDay > 0 && rule.ExpireMonth > 0 {
		return errors.New("can not set month and day one time")
	}

	values := []interface{}{
		id,
		rule.UserId,
		rule.UserId,
		rule.LoginStatus,
		string(formArr),
		string(lenArr),
	}
	if rule.ExpireDay > 0 {
		current := time.Now().Unix()
		total := current + int64(rule.ExpireDay * 24 * 3600)
		tm := time.Unix(total,0)
		expireStr := tm.Format("2006-01-02 15:04:05")
		values = append(values, expireStr)
		values = append(values, rule.ExpireDay)
	}

	if rule.ExpireMonth > 0 {
		sql = `insert into oauth_user_passwd_rule (id,created_by,
			user_id,login_status,passwd_form,passwd_length,passwd_expire,expire_month) 
			values($1,$2,$3,$4,$5,$6,$7,$8)`

		now := time.Now()
		expireDate := now.AddDate(0,rule.ExpireMonth,0)
		expireStr := expireDate.Format("2006-01-02 15:04:05")
		values = append(values, expireStr)
		values = append(values, rule.ExpireMonth)
	}

	err := s.db.Exec(sql,values...).Error
	if err != nil {
		logrus.Error(err)
		return err
	}

	return nil
}

func (s *ServiceImpl)GetPasswordRule() (*model.PassWordRule,error){
	querySql := `SELECT id,login_status,passwd_length,passwd_form,expire_day,
				 expire_month,passwd_expire 
				 FROM oauth_user_passwd_rule order by id desc limit 1 `
	rule := model.PassWordRule{}

	formStr,lenStr := "",""
	err := s.db.Raw(querySql).Row().Scan(&rule.Id,&rule.LoginStatus,
		&lenStr,&formStr,&rule.ExpireDay,&rule.ExpireMonth,&rule.PassWordExpire)
	if err != nil{
		if err == sql.ErrNoRows{
			logrus.Info("no rows found")
			return nil,nil
		}
		logrus.Error(err)
		return nil,err
	}

	err = json.Unmarshal([]byte(formStr),&rule.PassWordForm)
	if err != nil{
		logrus.Error(err)
		return nil,err
	}

	err = json.Unmarshal([]byte(lenStr),&rule.PassWordLength)
	if err != nil{
		logrus.Error(err)
		return nil,err
	}

	return &rule,nil
}

func (s *ServiceImpl)UpdatePasswordRule(ruleId uint64,rule *model.PassWordRule)(bool,error){
	values := make([]interface{},0)
	columns := make([]string,0)

	if rule.ExpireMonth > 0 && rule.ExpireDay > 0 {
		return false, errors.New("can not update month and month one time")
	}

	if rule.ExpireDay > 0 {
		columns = append(columns,"expire_day")
		values = append(values, rule.ExpireDay)
		//置空
		columns = append(columns,"expire_month")
		values = append(values, 0)

		current := time.Now().Unix()
		total := current + int64(rule.ExpireDay * 24 * 3600)
		tm := time.Unix(total,0)
		expireStr := tm.Format("2006-01-02 15:04:05")
		columns = append(columns,"passwd_expire")
		values = append(values, expireStr)

	}

	if rule.ExpireMonth > 0 {
		columns = append(columns,"expire_month")
		values = append(values, rule.ExpireMonth)
		// 置空
		columns = append(columns,"expire_day")
		values = append(values, 0)

		now := time.Now()
		expireDate := now.AddDate(0,rule.ExpireMonth,0)
		expireStr := expireDate.Format("2006-01-02 15:04:05")
		columns = append(columns,"passwd_expire")
		values = append(values, expireStr)
	}

	if len(rule.PassWordForm) > 0 {
		formArr,errM := json.Marshal(rule.PassWordForm)
		if errM != nil{
			logrus.Error(errM)
			return false,errM
		}

		columns = append(columns,"passwd_form")
		values = append(values, string(formArr))

	}

	if len(rule.PassWordLength) > 0{
		lenArr,errL := json.Marshal(rule.PassWordLength)
		if errL != nil{
			logrus.Error(errL)
			return false,nil
		}

		columns = append(columns,"passwd_length")
		values = append(values, string(lenArr))
	}

	if rule.LoginStatus > 0 {
		columns = append(columns,"login_status")
		values = append(values, rule.LoginStatus)
	}

	columns = append(columns,"updated_by")
	values = append(values, rule.UserId)


	sql := fmt.Sprintf("UPDATE oauth_user_passwd_rule SET %s WHERE id=%d",utils.CreateUpdateColumns(columns),ruleId)
	errU := s.db.Exec(sql,values...).Error
	if errU != nil{
		return false,errU

	}

	return true,nil
}







